const $ = jQuery = (function(window) {

  // dom存储
  function Query(doms, selector) {
    let i, len = doms ? doms.length : 0
    for (i = 0; i < len; i++) this[i] = doms[i]
    this.length = len
    this.selector = selector || ''
    return this
  }

  // 生成一个jquery对象
  function O(elements, selector) {
    return Query.call(this, elements, selector)
  }

  // 查找具体的dom
  function querySelectorAll(element, selector) {
    return element.querySelectorAll(selector)
  }

  O.prototype = {
    each(callback) {
      [].every.call(this, function(el, index) {
        return callback.call(el, index, el) !== false
      })
    },
    find(selector) {
      let doms = []
      this.each(function(index, el) {
        let childe = this.querySelectorAll(selector)
        doms.push(...childe)
      })
      return new O(doms, this.selector)
    },
    eq(i) {
      let doms = []
      this.each(function(index, el) {
        if (i == index) {
          doms.push(this)
        }
      })
      return new O(doms, this.selector)
    },
    remove() {
      this.each(function(index, el) {
        this.remove()
      })
    }
  }

  function isFunction(value) {
    return typeof value == 'function'
  }

  function $(nodeSelector) {
    let doms = querySelectorAll(document, nodeSelector)
    return new O(doms, nodeSelector)
  }

  $.isFunction = isFunction

  return $;
})()